import {createSlice} from "@reduxjs/toolkit";
import {setToken as _setToken,getToken,removeToken} from "@/utils";
import {getProfileApi, loginApi} from "@/apis/user";

const userStore=createSlice({
    name:'user',
    initialState:{
        token:getToken()||'',
        userInfo:{}
    },
    reducers:{
        setToken(state,action){
            state.token=action.payload
            _setToken(action.payload)
        },
        setUserInfo(state,action){
            state.userInfo=action.payload
        },
        clearUserInfo(state){
            state.token=''
            state.userInfo={}
            removeToken()
        }
    }
})

const {setToken,setUserInfo,clearUserInfo}=userStore.actions

const fetchLogin=(value)=>{
    return async (dispatch) => {
        const res=await loginApi(value)
        dispatch(setToken(res.data.token))
    }
}

const fetchUserInfo=()=>{
    return async (dispatch)=>{
        const res=await getProfileApi()
        dispatch(setUserInfo(res.data))
    }
}

export {fetchLogin,fetchUserInfo,clearUserInfo}

const userReducer=userStore.reducer
export default userReducer

